class_name EnemyStateMachine

enum State {
	IDLE,
	PATROL,
	CHASE,
	ATTACK,
	HURT,
	DEAD
}

var current_state: State = State.IDLE
var enemy: EnemyBase

func _init(enemy_node: EnemyBase):
	enemy = enemy_node

func handle_idle_state(delta: float):
	enemy.animated_sprite.play("idle")
	enemy.velocity.x = 0

func handle_patrol_state(delta: float):
	enemy.animated_sprite.play("run")
	# 简单的左右巡逻
	if !enemy.patrol_timer:
		enemy.patrol_timer = enemy.get_tree().create_timer(2.0)
		enemy.patrol_direction *= -1
	enemy.velocity.x = enemy.patrol_direction * enemy.move_speed

func handle_chase_state(delta: float):
	if enemy.player:
		enemy.animated_sprite.play("run")
		var direction = enemy.player.global_position.x - enemy.global_position.x
		enemy.velocity.x = sign(direction) * enemy.move_speed
		enemy.animated_sprite.flip_h = direction < 0
	else:
		current_state = State.IDLE

func handle_attack_state(delta: float):
	if enemy.can_attack and enemy.player:
		enemy.animated_sprite.play("attack")
		# 具体的攻击逻辑在各个敌人子类中实现

func update(delta: float):
	match current_state:
		State.IDLE:
			handle_idle_state(delta)
		State.PATROL:
			handle_patrol_state(delta)
		State.CHASE:
			handle_chase_state(delta)
		State.ATTACK:
			handle_attack_state(delta)
